//
//  CardDetialViewController.m
//  LikeAttention
//
//  Created by 于金祥 on 15/8/11.
//  Copyright (c) 2015年 zykj.LikeAttention. All rights reserved.
//

#import "CardDetialViewController.h"
#import "UIImageView+WebCache.h"
#import "DataProvider.h"
#import "QRCodeGenerator.h"
#import "LoginViewController.h"
#import "SVProgressHUD.h"
#import "Model_cardDetail.h"

#define DEFAULT_VOID_COLOR [UIColor whiteColor]

@interface CardDetialViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>

@property (nonatomic, strong) NSMutableArray * arr_data;

@property (nonatomic, assign) BOOL iscell_1;

@property (nonatomic, assign) BOOL iscell_2;

@property (nonatomic, assign) BOOL iscell_3;

@end

@implementation CardDetialViewController
{
    NSUserDefaults * userdefaults;
    NSString * youhuiDetial;
    NSString * shiyongMustKnow;
    NSString * mengdian;
    NSDictionary * cardDetial;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [SVProgressHUD dismiss];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"HUDDismiss" object:nil];
    _myTableview.tableFooterView = [[UIView alloc] init];

    [self p_data];
    
    userdefaults = [[NSUserDefaults alloc] init];
    
    [self p_navigationController];
}

#pragma mark - navigationController
- (void)p_navigationController
{
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    self.navigationItem.title = @"卡券详情";
    UIButton * btn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [btn setBackgroundImage:[UIImage imageNamed:@"返回"] forState:(UIControlStateNormal)];
        btn.frame = CGRectMake(10, 20, 25, 30);
    [btn addTarget:self action:@selector(leftBarButtonItemAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
}
//点击事件(左)
- (void)leftBarButtonItemAction:(UIBarButtonItem *)bar
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 布局
-(void)BuildHeaderView
{

    Model_cardDetail * model = self.arr_data.firstObject;
    
    UIView * headerview=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 400)];
    UIView * firstview=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
    firstview.backgroundColor = [self colorWithHexString:model.couponcolor];
    UIImageView * store_logo=[[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 60, 60)];
    store_logo.layer.masksToBounds=YES;
    store_logo.layer.cornerRadius=30;
    [firstview addSubview:store_logo];
    
    NSString *url = [NSString stringWithFormat:@"%@upload/%@",Url,model.couponimage];
    [store_logo sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"头像"]];
    
    UILabel * lbl_storetitle=[[UILabel alloc] initWithFrame:CGRectMake(store_logo.frame.size.width+store_logo.frame.origin.x+10, 40, SCREEN_WIDTH - store_logo.frame.size.width - store_logo.frame.origin.x - 20, 20)];
    lbl_storetitle.text= model.name;
//    lbl_storetitle.backgroundColor = [UIColor redColor];
    lbl_storetitle.textColor=[UIColor whiteColor];
    [firstview addSubview:lbl_storetitle];
    
//    UILabel * lbl_juli=[[UILabel alloc] initWithFrame:CGRectMake(firstview.frame.size.width-140, 40, 120, 20)];
//    lbl_juli.textColor=[UIColor whiteColor];
//    lbl_juli.text=@"距离500米";
//    lbl_juli.textAlignment=NSTextAlignmentRight;
//    [firstview addSubview:lbl_juli];
    
    UILabel * lbl_activeTitle=[[UILabel alloc] initWithFrame:CGRectMake(0, store_logo.frame.size.height+store_logo.frame.origin.y, firstview.frame.size.width, 40)];
    lbl_activeTitle.text= model.couponname;
    lbl_activeTitle.textAlignment=NSTextAlignmentCenter;
    lbl_activeTitle.textColor=[UIColor whiteColor];
    lbl_activeTitle.font=[UIFont systemFontOfSize:22];
    [firstview addSubview:lbl_activeTitle];
    
    UILabel * lbl_youxiaoqi=[[UILabel alloc] initWithFrame:CGRectMake(0, lbl_activeTitle.frame.size.height+lbl_activeTitle.frame.origin.y+15, firstview.frame.size.width, 20)];
    lbl_youxiaoqi.text=[NSString stringWithFormat:@"有效期: %@",model.effecttime];
    lbl_youxiaoqi.textAlignment=NSTextAlignmentCenter;
    lbl_youxiaoqi.textColor=[UIColor whiteColor];
    lbl_youxiaoqi.font=[UIFont systemFontOfSize:15];
    [firstview addSubview:lbl_youxiaoqi];
    UILabel * lbl_guoqi=[[UILabel alloc] initWithFrame:CGRectMake(0, lbl_youxiaoqi.frame.size.height+lbl_youxiaoqi.frame.origin.y+15, firstview.frame.size.width, 20)];
    lbl_guoqi.text= model.remind;
    lbl_guoqi.textAlignment=NSTextAlignmentCenter;
    lbl_guoqi.textColor=[UIColor whiteColor];
    lbl_guoqi.font=[UIFont systemFontOfSize:15];
    [firstview addSubview:lbl_guoqi];
    
    UIImageView * img_huabian=[[UIImageView alloc] initWithFrame:CGRectMake(0, firstview.frame.size.height- 3, firstview.frame.size.width, 10)];
    img_huabian.image=[UIImage imageNamed:@"huabian_.png"];
    [firstview addSubview:img_huabian];
    [headerview addSubview:firstview];
    
    
    UIView * secondView=[[UIView alloc] initWithFrame:CGRectMake(0, firstview.frame.size.height+firstview.frame.origin.y, SCREEN_WIDTH, 170)];
    secondView.backgroundColor=[UIColor whiteColor];
    UIImageView * img_erweima=[[UIImageView alloc] initWithFrame:CGRectMake((secondView.frame.size.width-150)/2, 10, 150, 150)];

    img_erweima.image=[QRCodeGenerator qrImageForString:[NSString stringWithFormat:@"%@",model.couponnum] imageSize:img_erweima.bounds.size.width];
    [secondView addSubview:img_erweima];
    
    UILabel * lbl_shuomingDetial=[[UILabel alloc] initWithFrame:CGRectMake(0, img_erweima.frame.size.height+img_erweima.frame.origin.y+10, SCREEN_WIDTH, 20)];
    lbl_shuomingDetial.text=[NSString stringWithFormat:@"%@",model.couponnum];
    lbl_shuomingDetial.textAlignment=NSTextAlignmentCenter;
    lbl_shuomingDetial.textColor=[UIColor grayColor];
    lbl_shuomingDetial.numberOfLines=0;
    [secondView addSubview:lbl_shuomingDetial];
    [headerview addSubview:secondView];
    
    _myTableview.tableHeaderView=headerview;
    
    _myTableview.delegate = self;
    _myTableview.dataSource = self;
    
    [_myTableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell_cardDetail"];
}

#pragma mark - tableView

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Model_cardDetail * model = self.arr_data.firstObject;
    
    if (indexPath.section==0&&indexPath.row==0) {
        
        if(self.iscell_1 == 0)
        {
            youhuiDetial= model.coupondetail;
            [tableView reloadSections:[[NSIndexSet alloc]initWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
            
            self.iscell_1 = 1;
            
        }
        else
        {
            youhuiDetial = nil;
            [tableView reloadSections:[[NSIndexSet alloc]initWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
            
            self.iscell_1 = 0;
        }
        
    }
    
    if (indexPath.section==1&&indexPath.row==0) {
        //        shiyongMustKnow=cardDetial[@"couponintroduct"];
        //        [tableView reloadSections:[[NSIndexSet alloc]initWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
        
        if(self.iscell_2 == 0)
        {
            shiyongMustKnow= model.couponintroduct;
            [tableView reloadSections:[[NSIndexSet alloc]initWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
            
            self.iscell_2 = 1;
            
        }
        else
        {
            shiyongMustKnow = nil;
            [tableView reloadSections:[[NSIndexSet alloc]initWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
            
            self.iscell_2 = 0;
        }
    }
    
    
    if (indexPath.section==2&&indexPath.row==0) {
        //        shiyongMustKnow=cardDetial[@"couponintroduct"];
        //        [tableView reloadSections:[[NSIndexSet alloc]initWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
        
        if(self.iscell_3 == 0)
        {
            
            if([model.storename length] == 0)
            {
                mengdian = @"";
            }
            else
            {
                mengdian= [NSString stringWithFormat:@"%@",model.storename];
            }
            
            
            
            [tableView reloadSections:[[NSIndexSet alloc]initWithIndex:2] withRowAnimation:UITableViewRowAnimationAutomatic];
            
            self.iscell_3 = 1;
            
        }
        else
        {
            mengdian = nil;
            [tableView reloadSections:[[NSIndexSet alloc]initWithIndex:2] withRowAnimation:UITableViewRowAnimationAutomatic];
            
            self.iscell_3 = 0;
        }
    }
    
    
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height=44;
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            height=44 ;
        }
        else
        {
            height=100;
        }
    }else if (indexPath.section==1){
        if (indexPath.row==0) {
            height=44;
        }else
        {
            height=100;
        }
    }else if (indexPath.section==2){
        if (indexPath.row==0) {
            height=44;
        }else
        {
            height=100;
        }
    }
    else if(indexPath.section == 3)
    {
        height = 80;
    }
    else
    {
        height = 50;
    }
    return height;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Model_cardDetail * model = self.arr_data.firstObject;
    
    UITableViewCell * cell=[[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//cell的右边有一个小箭头，距离右边有十几像素；
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            cell.textLabel.text=@"优惠详情";
        }
        else
        {
            if (youhuiDetial) {
                cell.accessoryType = UITableViewCellAccessoryNone;//cell没有任何的样式
                cell.backgroundColor= [UIColor whiteColor];
                UIView * backview=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
                UITextView * txt_youhuixiangqing=[[UITextView alloc] initWithFrame:CGRectMake(20, 10, SCREEN_WIDTH-40, 80)];
                txt_youhuixiangqing.backgroundColor=[UIColor whiteColor];
                txt_youhuixiangqing.text=youhuiDetial;
                txt_youhuixiangqing.scrollEnabled=YES;
                [txt_youhuixiangqing setEditable:NO];
                [backview addSubview:txt_youhuixiangqing];
                [cell addSubview:txt_youhuixiangqing];
                return  cell;
            }
            else
            {
                return nil;
            }
        }
    }
    else if (indexPath.section==1)
    {
        if (indexPath.row==0) {
            cell.textLabel.text=@"使用须知";
        }
        else
        {
            if (shiyongMustKnow) {
                cell.accessoryType = UITableViewCellAccessoryNone;//cell没有任何的样式
                cell.backgroundColor= [UIColor whiteColor];
                UIView * backview=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
                UITextView * txt_youhuixiangqing=[[UITextView alloc] initWithFrame:CGRectMake(20, 10, SCREEN_WIDTH-40, 80)];
                txt_youhuixiangqing.backgroundColor=[UIColor whiteColor];
                txt_youhuixiangqing.text=shiyongMustKnow;
                txt_youhuixiangqing.scrollEnabled=YES;
                [txt_youhuixiangqing setEditable:NO];
                [backview addSubview:txt_youhuixiangqing];
                [cell addSubview:txt_youhuixiangqing];
                return  cell;
            }
            else
            {
                return nil;
            }
        }
    }else if (indexPath.section==2)
    {
        if (indexPath.row==0) {
            cell.textLabel.text= @"适合门店";
        }
        else
        {
            if (mengdian) {
                cell.accessoryType = UITableViewCellAccessoryNone;//cell没有任何的样式
                cell.backgroundColor= [UIColor whiteColor];
                UIView * backview=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
                UITextView * txt_youhuixiangqing=[[UITextView alloc] initWithFrame:CGRectMake(20, 10, SCREEN_WIDTH-40, 80)];
                txt_youhuixiangqing.backgroundColor=[UIColor whiteColor];
                txt_youhuixiangqing.text=mengdian;
                txt_youhuixiangqing.scrollEnabled=YES;
                [txt_youhuixiangqing setEditable:NO];
                [backview addSubview:txt_youhuixiangqing];
                [cell addSubview:txt_youhuixiangqing];
                return  cell;
            }
            else
            {
                return nil;
            }
        }
    }
    else if(indexPath.section == 3)
    {
        
        cell.accessoryType = UITableViewCellAccessoryNone;//cell没有任何的样式
        UILabel *lbl_storeTitle=[[UILabel alloc] initWithFrame:CGRectMake(20, 10, SCREEN_WIDTH-80, 20)];
        lbl_storeTitle.text= @"产品名称";
        [cell addSubview:lbl_storeTitle];
        UILabel * lbl_storeAddress=[[UILabel alloc] initWithFrame:CGRectMake(20, lbl_storeTitle.frame.size.height+lbl_storeTitle.frame.origin.y+10, SCREEN_WIDTH-80, 20)];
        lbl_storeAddress.font=[UIFont systemFontOfSize:14];
        lbl_storeAddress.textColor=[UIColor grayColor];
        lbl_storeAddress.text= model.address;
        [cell addSubview:lbl_storeAddress];
        UIButton * img_makeCall=[[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-70, 0, 70, 80)];
        [img_makeCall setImage:[UIImage imageNamed:@"Call_icon"] forState:UIControlStateNormal];
        [img_makeCall addTarget:self action:@selector(makeCall:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:img_makeCall];
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;//cell没有任何的样式
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIButton * btn = [UIButton buttonWithType:(UIButtonTypeSystem)];
        btn.frame = CGRectMake(5, 0, SCREEN_WIDTH - 10, 50);
        btn.layer.cornerRadius = 5;
        btn.titleLabel.font = [UIFont systemFontOfSize:19];
        [btn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        btn.backgroundColor = [self colorWithHexString:model.couponcolor];
        
        switch ([model.state intValue]) {
            case -1:
            {
                [btn setTitle:@"待领取" forState:(UIControlStateNormal)];
            }
                break;
            case 0:
            {
                [btn setTitle:@"未使用" forState:(UIControlStateNormal)];
                
                [btn addTarget:self action:@selector(btnAction:) forControlEvents:(UIControlEventTouchUpInside)];
                
            }
                break;
            case 1:
            {
                [btn setTitle:@"赠送中" forState:(UIControlStateNormal)];
            }
                break;
            case 2:
            {
                [btn setTitle:@"已使用" forState:(UIControlStateNormal)];
            }
                break;
            case 3:
            {
                [btn setTitle:@"已过期" forState:(UIControlStateNormal)];
            }
                break;
        }
        [cell addSubview:btn];
    }
    return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        if (youhuiDetial) {
            return 2;
        }
        else
        {
            return 1;
        }
    }else if (section==1){
        if (shiyongMustKnow) {
            return 2;
        }else
        {
            return 1;
        }
    }
    else if (section==2){
        if (mengdian) {
            return 2;
        }else
        {
            return 1;
        }
    }
    else{
        return 1;
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}


-(void)makeCall:(UIButton *)sender
{
    Model_cardDetail * model = self.arr_data.firstObject;

    
    UIAlertView * alert=[[UIAlertView alloc] initWithTitle:@"提示" message:model.telephone delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"呼叫", nil];
    [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        // 直接拨号，拨号完成后会停留在通话记录中
        Model_cardDetail * model = self.arr_data.firstObject;
        
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",model.telephone]];
        
        [[UIApplication sharedApplication] openURL:url];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 点击
- (void)btnAction:(UIButton *)sender
{
    [self p_data1];
}

- (void)p_data1
{
    Model_cardDetail * model = self.arr_data.firstObject;
    
    DataProvider * dataprovider = [[DataProvider alloc] init];
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    
    [dataprovider setDelegateObject:self setBackFunctionName:@"CardDalloc:"];
    
    [dataprovider couponConsumeWithMerchantid:[defaults objectForKey:@"merchantid"] couponid:model.couponid];
}

- (void)CardDalloc:(id )dict
{
//    NSLog(@"%@",dict);
    
    if ([dict[@"status"][@"succeed"] intValue] == 1) {
        @try
        {
            [SVProgressHUD showSuccessWithStatus:@"使用成功" maskType:(SVProgressHUDMaskTypeBlack)];
            
            [self p_data];
        }
        @catch (NSException *exception) {
            
        }
        @finally {
            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                //刷新tableView(记住,要更新放在主线程中)
//                
//                [self.myTableview reloadData];
//            });
        }
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:dict[@"status"][@"errdesc"] maskType:SVProgressHUDMaskTypeBlack];
    }
}



#pragma mark - 数据
- (void)p_data
{
    DataProvider * dataprovider = [[DataProvider alloc] init];
    
    [dataprovider setDelegateObject:self setBackFunctionName:@"coupondetail:"];
    
    [dataprovider coupondetailWithCouponid:self.couponid];
}

- (void)coupondetail:(id )dict
{
    NSLog(@"%@",dict);
    
    self.arr_data = nil;
    
    if ([dict[@"status"][@"succeed"] intValue] == 1) {
        @try
        {
            NSDictionary * dic = dict[@"data"];
            
            Model_cardDetail * model = [[Model_cardDetail alloc] init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [self.arr_data addObject:model];
            
        }
        @catch (NSException *exception) {
            
        }
        @finally
        {
            Model_cardDetail * model1 = self.arr_data.firstObject;
            
            if([[NSString stringWithFormat:@"%@",model1.couponid] length] == 0)
            {
                [SVProgressHUD showErrorWithStatus:@"该卡券号无信息" maskType:SVProgressHUDMaskTypeBlack];
            }
            else
            {
                [self BuildHeaderView];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //刷新tableView(记住,要更新放在主线程中)
                
                [self.myTableview reloadData];
            });
        }
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:dict[@"status"][@"errdesc"] maskType:SVProgressHUDMaskTypeBlack];
    }
}

#pragma mark - 懒加载
- (NSMutableArray *)arr_data
{
    if(_arr_data == nil)
    {
        self.arr_data = [NSMutableArray array];
    }
    
    return _arr_data;
}


#pragma mark - 颜色转换
- (UIColor *)colorWithHexString:(NSString *)stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    
    if ([cString length] < 6)
        return DEFAULT_VOID_COLOR;
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return DEFAULT_VOID_COLOR;
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}


















@end
